<template>
  <CDialog
    :title="title"
    v-model:visible="dialogVisible"
    :loading="loading"
    confirmText="保存"
    cancelText="关闭"
    @confirm="handleConfirm"
    @cancel="dialogVisible = false"
  >
    <el-form ref="formRef" :model="formState" :rules="rules" label-position="top">
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="字典类型" prop="dataType">
            <CSelect v-model="formState.dataType" placeholder="请选择" clearable>
              <el-option
                v-for="item in filedList"
                :key="item.id"
                :label="item.dataDesc"
                :value="`${item.dataGroup ? item.dataGroup : ''}-${item.dataType}`"
              />
            </CSelect>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="字典代码" prop="dataCode">
            <el-input
              v-model.trim="formState.dataCode"
              type="text"
              placeholder="请输入"
              clearable
              maxlength="255"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="值名称" prop="dataValue">
            <el-input
              v-model.trim="formState.dataValue"
              type="text"
              placeholder="请输入"
              clearable
              maxlength="255"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="值描述">
            <el-input
              v-model.trim="formState.dataDesc"
              type="text"
              placeholder="请输入"
              clearable
              maxlength="255"
            />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item label="上级字典关联值" prop="parentId">
            <FieldSelect v-model:value="formState.parentId" placeholder="请输入" />
          </el-form-item>
        </el-col> -->
        <el-col :span="12">
          <el-form-item label="排序">
            <el-input-number
              class="input-number"
              :min="0"
              :step="1"
              style="width: 100%"
              v-model="formState.sort"
            />
            <!-- <el-input v-model="formState.sort" type="number" placeholder="请输入" clearable /> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="启用状态">
            <!-- <el-switch v-model="formState.enableFlag" /> -->
            <CSelect v-model="formState.enableFlag" placeholder="请选择" clearable>
              <el-option
                v-for="item in enableOption"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </CSelect>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input
              v-model.trim="formState.remark"
              placeholder="请输入"
              :rows="2"
              type="textarea"
              maxlength="255"
              show-word-limit
              resize="none"
            /> </el-form-item
        ></el-col>
      </el-row>
    </el-form>
  </CDialog>
</template>

<script lang="ts" setup name="SystemFieldDialog">
import { withDefaults, defineProps, defineEmits, computed, watch, reactive, ref } from 'vue';
import { CDialog } from '@/components/CDialog';
import { useMessage } from '@/hooks/useMessage';
import { rules } from './rules';
import { CSelect } from '@/components/CSelect';
import { enableOption } from '@/constants/enum';
import { getDictTypeList, editDict, createDict } from '@/apis/system/dataDict';
import FieldSelect from '../../FieldSelect/index.vue';
import { IDictItemResult } from '@/apis/system/dataDict/model/dataDictModel';

interface GeographicDialogProps {
  visible: boolean;
  nodeItem?: IDictItemResult;
  dataType: string;
}
const props = withDefaults(defineProps<GeographicDialogProps>(), {});
const emits = defineEmits(['update:visible', 'refresh']);

const { createMessage, createConfirm } = useMessage();
const dialogVisible = computed({
  get: () => {
    return props.visible;
  },
  set: (value: boolean) => {
    emits('update:visible', value);
  }
});
watch(
  () => dialogVisible.value,
  val => {
    if (val) {
      loadFiledList();
      init();
    } else {
      formRef.value?.resetFields();
    }
  }
);

const formRef = ref();
const loading = ref(false);
/**
 * 表单内容
 */
const formState = reactive({
  dataType: '',
  dataCode: '',
  dataValue: '',
  sort: 0,
  dataDesc: '',
  remark: '',
  enableFlag: true,
  // parentId: [] as string[],
  parentGroup: ''
});

/**
 * 弹窗标题
 */
const title = computed(() => {
  return props.nodeItem ? '编辑系统字段' : '新增系统字段';
});

const filedList = ref<any[]>([]);
const loadFiledList = async () => {
  const data = await getDictTypeList();
  filedList.value = data ?? [];
};
/**
 * 初始化
 */
function init() {
  loading.value = false;
  if (props.nodeItem) {
    getData(props.nodeItem);
  } else {
    formState.dataType = props.dataType || '';
    formState.dataValue = '';
    formState.dataDesc = '';
    formState.remark = '';
    formState.enableFlag = true;
    // formState.parentId = [];
    formState.dataCode = '';
    formState.sort = 0;
    formState.parentGroup = '';
  }
}

/**
 * 获取节点详情
 */
async function getData(nodeItem: IDictItemResult) {
  try {
    formState.dataType = `${nodeItem.dataGroup ? nodeItem.dataGroup : ''}-${nodeItem.dataType}`;
    formState.dataValue = nodeItem.dataValue;
    formState.dataCode = nodeItem.dataCode;
    formState.dataDesc = nodeItem.dataDesc;
    formState.remark = nodeItem.remark;
    formState.enableFlag = nodeItem.enableFlag;
    // formState.parentId = [`${nodeItem.parentGroup}-${nodeItem.parentDataType}`, nodeItem.parentId];
    formState.sort = nodeItem.sort;
  } catch (error) {
    console.log('error', error);
    loading.value = false;
  }
}

/**
 * 保存按钮
 */
function handleConfirm() {
  console.log('handleConfirm');
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      handleEditNodeReq();
    }
  });
}

/**
 * 实际修改请求提交
 */
async function handleEditNodeReq() {
  try {
    const params: any = {
      ...formState,
      dataGroup: formState.dataType.split('-')[0],
      dataType: formState.dataType.split('-')[1]
    };
    // if (formState.parentId.length) {
    //   const parentArr = formState.parentId[0].split('-');
    //   params.parentDataType = parentArr[1];
    //   params.parentGroup = parentArr[0];
    //   params.parentId = formState.parentId[1];
    // } else {
    //   params.parentId = '';
    // }
    if (!props.nodeItem) {
      await createDict(params);
    } else {
      params.id = props.nodeItem.id;
      await editDict(params);
    }
    createMessage.success(props.nodeItem ? '编辑成功！' : '新增成功！');
    emits('refresh');
    loading.value = false;
    dialogVisible.value = false;
  } catch (error) {
    console.log('error', error);
    loading.value = false;
  }
}
</script>
